import { NslUtils } from "@/utils/NslUtil";
import { NslUtil4Vue } from "@/utils/NslUtil4Vue";
import { TypeRouteRecordRawWithFullPath } from "@/utils/util_type";
import {
    RouteLocationNormalizedLoaded,
    RouteRecordRaw,
    Router,
} from "vue-router";
import { useTagViewStoreWithSetup } from "@/store/modules/tag-view-store";
// import { router } from "@/routes/routes_index";
import { storeToRefs } from "pinia";
import { nextTick } from "vue";

let router: Router, route;
let elScrollWrapDom: HTMLDivElement, tagAndTagSpacing: number;

const tagViewStore = useTagViewStoreWithSetup();
const { visitedViews } = storeToRefs(tagViewStore);

// let tagViewStore,visitedViews;

export function initAffixTags(tagRoutes: RouteRecordRaw[]) {
    const affixRoutes = getAffixRoutes(tagRoutes);
    affixRoutes.forEach((r) => {
        tagViewStore.addVisitedView(fullPathRoute2TagView(r));
    });
}

export function initTsParameters(
    routerP: Router,
    routeP: RouteLocationNormalizedLoaded,
    elScrollWrapDomP: HTMLDivElement,
    tagAndTagSpacingP: number
) {
    // tagViewStore=useTagViewStoreWithSetup();
    // visitedViews=storeToRefs(tagViewStore).visitedViews;
    (router = routerP), (route = routeP);
    elScrollWrapDom = elScrollWrapDomP;
    tagAndTagSpacing = tagAndTagSpacingP;
}

export function pushRouteAndMove2Tag(fullPath: string) {
    moveToCurrentTag(fullPath);
    if (router.currentRoute.value.fullPath !== fullPath) {
        router.push({ path: fullPath });
    }
}
export function moveToCurrentTag(fullPath: string) {
    //这里为什么用nextTick
    //试想一下，在tag将要填满时，此时route更新，会发生以下步骤
    //1.visitedViews 增加一项
    //2 moveToCurrentTag(),此时新的tag dom元素还未渲染出来，滚动条还未出现,scrollWidth=offsetWidth,scrollLeft=0，因为界面还没重新渲染
    //3.界面重新渲染，新tag超出了tag 容器，出现滚动条，但scrollLeft=0,滚动条位置不正确
    //原因分析：moveToCurrentTag() 在页面渲染前运行，
    //解决办法： 将2/3步骤调换次序，先渲染页面，再运行moveToCurrentTag()
    nextTick(() => {
        visitedViews.value.forEach((e) => {
            //todo: fix bug,未考虑query参数情况
            if (e.fullPath === fullPath) {
                moveToTarget(elScrollWrapDom, e, tagAndTagSpacing);
            }
        });
    });
}

export function fullPathRoute2TagView(
    fullPathRoute:
        | RouteLocationNormalizedLoaded
        | TypeRouteRecordRawWithFullPath
) {
    return {
        name: fullPathRoute.name as string,
        title: fullPathRoute.meta?.title as string,
        path: fullPathRoute.path,
        fullPath: fullPathRoute.fullPath,
        affix: NslUtils.toBoolean(fullPathRoute.meta?.affix),
        keepAlive: NslUtils.toBoolean(fullPathRoute.meta?.keepAlive),
    };
}

//初始化tag view 显示，保留affix=true的tag
export function getAffixRoutes(routes: RouteRecordRaw[]) {
    const affixRoutes: TypeRouteRecordRawWithFullPath[] = [];
    const menuTestFullPathRoutes = NslUtil4Vue.buildFullPathRoutes(routes);

    const filterFn = (routeArray: TypeRouteRecordRawWithFullPath[]) => {
        routeArray.forEach((r) => {
            if (r.meta && r.meta.affix) {
                affixRoutes.push(r);
            }
            if (r.children && r.children.length > 0) {
                filterFn(r.children);
            }
        });
    };

    filterFn(menuTestFullPathRoutes);
    return affixRoutes;
}

// 根据点击的tag，scroll到相应的位置
export function moveToTarget(
    elScrollWrapDom: HTMLDivElement,
    targetTag: TypeTagViewI,
    tagAndTagSpacing: number
) {
    const elScrollWrapDomWidth = elScrollWrapDom.offsetWidth;

    // console.log('in moveToTarget');
    // console.log('elScrollWrapDom.scrollWidth',elScrollWrapDom.scrollWidth);
    // console.log('elScrollWrapDomWidth',elScrollWrapDomWidth);

    let firstTag = null;
    let lastTag = null;
    if (tagViewStore.visitedViews.length > 0) {
        firstTag = tagViewStore.visitedViews[0];
        lastTag =
            tagViewStore.visitedViews[tagViewStore.visitedViews.length - 1];
    }

    if (firstTag === targetTag) {
        elScrollWrapDom.scrollLeft = 0;
    } else if (lastTag === targetTag) {
        // console.log('in moveToTarget last');
        elScrollWrapDom.scrollLeft =
            elScrollWrapDom.scrollWidth - elScrollWrapDomWidth;
        //console.log(' elScrollWrapDom.scrollLeft', elScrollWrapDom.scrollLeft);
    } else {
        let currenIndex = tagViewStore.visitedViews.findIndex(
            (item) => item === targetTag
        );

        let prevTagDom = null;
        let nextTagDom = null;
        const tagDomList = elScrollWrapDom.getElementsByClassName("tags-item");

        prevTagDom = tagDomList[currenIndex - 1] as HTMLDivElement;
        nextTagDom = tagDomList[currenIndex + 1] as HTMLDivElement;

        // the tag's offsetLeft after of nextTag
        const afterNextTagOffsetLeft =
            nextTagDom!.offsetLeft + nextTagDom!.offsetWidth + tagAndTagSpacing;

        // the tag's offsetLeft before of prevTag
        const beforePrevTagOffsetLeft =
            prevTagDom!.offsetLeft - tagAndTagSpacing;

        if (
            afterNextTagOffsetLeft >
            elScrollWrapDom.scrollLeft + elScrollWrapDomWidth
        ) {
            elScrollWrapDom.scrollLeft =
                afterNextTagOffsetLeft - elScrollWrapDomWidth;
        } else if (beforePrevTagOffsetLeft < elScrollWrapDom.scrollLeft) {
            elScrollWrapDom.scrollLeft = beforePrevTagOffsetLeft;
        }
    }
}

export function isAffix(tag: TypeTagViewI) {
    return tag?.affix;
}

export function closeSelectedTag(
    tag: TypeTagViewI,
    currentFullPath: string,
    defaultRoutePath: string = "/"
) {
    tagViewStore.delVisitedView(tag).then(() => {
        if (visitedViews.value.length > 0) {
            if (isActive(tag, currentFullPath)) {
                const latestView =
                    visitedViews.value[visitedViews.value.length - 1];
                router.push(latestView.fullPath);
            }
        } else {
            router.push(defaultRoutePath);
        }
    });
}

export function isActive(tag: TypeTagViewI, currentFullPath: string) {
    return tag.fullPath === currentFullPath;
}
